package com.example.im.ui.adapter

import android.content.Context
import android.text.Html
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.im.R
import com.example.im.common.ImApplication
import com.example.im.entity.ChatContent
import com.example.im.entity.ChatRecordLast
import com.example.im.utils.JsonUtils
import com.example.im.utils.LogUtils
import com.xlkj.ehobe.storage.ui.adapter.holder.RecyclerViewHolder
import kotlinx.android.synthetic.main.recycler_item_chat_user.view.*
import org.jivesoftware.smack.packet.Message
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.abs
import kotlin.math.min


class ChatUserAdapter(
    private val mContext: Context,
    private val lasts: MutableList<ChatRecordLast>
) :
    RecyclerView.Adapter<RecyclerViewHolder>() {


    private var mOnClickItemListener: OnClickItemListener? = null

    fun setOnItemClickListener(mOnClickItemListener: OnClickItemListener) {
        this.mOnClickItemListener = mOnClickItemListener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
        return RecyclerViewHolder(
            LayoutInflater.from(mContext).inflate(
                R.layout.recycler_item_chat_user, parent, (false)
            )
        )
    }

    override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {

        val view: View = holder.itemView

        val last = lasts[position]

        val content = JsonUtils.stringToObject(
            last.body, ChatContent::class.java
        )
        val name = ImApplication.appDatabase().friendOrRoomDao()
            .selectFriendOrRoomById(last.fId).nickname

        if (last.type == Message.Type.chat.ordinal) {
            view.img_user_heard.setImageResource(R.drawable.ic_touxiang)
        } else {
            view.img_user_heard.setImageResource(R.drawable.ic_group_touxiang)
        }

        val recordEntires = ImApplication.appDatabase().chatRecordEntireDao()
            .selectChatRecordEntireItel(last.id)
        var itel = ""
        recordEntires.forEach {
            val account = ImApplication.appDatabase().accountDao().account()
            if (it.itel!!.contains(account.username!!)) {
                itel = "<font color=#ff0000>[有人@你]</font>"
            }
        }
        view.tv_name.text = name
        val spanned =
            Html.fromHtml(if (last.name == null) content.body else "$itel${last.name}: ${content.body}")
        view.tv_text.text = spanned
        view.tv_time.text = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
            .format(Date(last.time))
        val count = ImApplication.appDatabase().chatRecordEntireDao().count(last.id)
        if (count == 0) {
            view.tv_count.visibility = View.GONE
        } else {
            if (count > 100) {
                view.tv_count.text = "···"
            } else {
                view.tv_count.text = count.toString()
            }
            view.tv_count.visibility = View.VISIBLE
        }
        view.setOnClickListener { v ->
            mOnClickItemListener!!.onClickItem(v, position)
        }
        view.tag = position
    }

    override fun getItemCount(): Int {
        return lasts.size
    }

    fun addDataItem(last: ChatRecordLast) {
        if (this.lasts.none { it.id == last.id }) {
            this.lasts.add(0, last)
            this.notifyDataSetChanged()
        } else for ((index, value) in this.lasts.withIndex()) if (value.id == last.id) {
            this.lasts[index] = last
            for (i in index downTo 1) {
                Collections.swap(this.lasts, i, (i - 1))
            }
            this.notifyItemRangeChanged(min(index, 0), abs(index - 0) + 1)
        }
    }

    fun upDataItem(last: ChatRecordLast) {
        for ((index, value) in this.lasts.withIndex()) if (value.id == last.id) {
            this.lasts[index] = last
            this.notifyItemChanged(index)
        }
    }

    fun removeDataItem(f_id: Int) {
        for ((index, value) in this.lasts.withIndex()) if (value.fId == f_id) {
            this.lasts.removeAt(index)
            this.notifyItemRangeChanged(index, itemCount + 1)
            return
        }
    }

    fun clearData() {
        this.lasts.clear()
        this.notifyDataSetChanged()
    }


    interface OnClickItemListener {
        fun onClickItem(view: View, position: Int)
    }
}
